package com.example.webmodule.util;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.example.webmodule.entity.ApiPathVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class OpenApiProcessor {
    public static List<ApiPathVo> processOpenApi(String openApiJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<ApiPathVo> list = Lists.newArrayList();
        try {
            JsonNode rootNode = objectMapper.readTree(openApiJson);
            JsonNode pathsNode = rootNode.path("paths");
            Iterator<Map.Entry<String, JsonNode>> pathsIterator = pathsNode.fields();
            while (pathsIterator.hasNext()) {

                Map.Entry<String, JsonNode> pathEntry = pathsIterator.next();
                String path = pathEntry.getKey();
                JsonNode methodsNode = pathEntry.getValue();

                Iterator<Map.Entry<String, JsonNode>> methodsIterator = methodsNode.fields();
                while (methodsIterator.hasNext()) {
                    Map.Entry<String, JsonNode> methodEntry = methodsIterator.next();
                    String method = methodEntry.getKey();
                    JsonNode methodDetailsNode = methodEntry.getValue();
                    ApiPathVo apiPathVo = ApiPathVo.builder().path(path).method(method)
                            .tags(methodDetailsNode.path("tags").toString())
                            .operationId(methodDetailsNode.path("operationId").asText())
                            .build();
                    list.add(apiPathVo);
//                    JsonNode responsesNode = methodDetailsNode.path("responses");
//                    Iterator<Map.Entry<String, JsonNode>> responsesIterator = responsesNode.fields();
//                    while (responsesIterator.hasNext()) {
//                        Map.Entry<String, JsonNode> responseEntry = responsesIterator.next();
//                        String responseCode = responseEntry.getKey();
//                        JsonNode responseDetailsNode = responseEntry.getValue();
//
//                        System.out.println("    Response Code: " + responseCode);
//                        System.out.println("      Description: " + responseDetailsNode.path("description"));
//                        System.out.println("      Content: " + responseDetailsNode.path("content"));
//                    }
                }
            }
        } catch (IOException e) {
        }
        return list;
    }
}
